package database

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"insighttracking/query/dao"
	"net/url"
)

func NewMysqlDB(username, password, host, port, database, charset, loc string) *gorm.DB {
	// 字符串拼接
	dataSource := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=true&loc=%s",
		username,
		password,
		host,
		port,
		database,
		charset,
		url.QueryEscape(loc),
	)
	fmt.Println(dataSource, "数据库连接")
	db, err := gorm.Open(mysql.Open(dataSource), &gorm.Config{
		Logger:                                   logger.Default.LogMode(logger.Info),
		DisableForeignKeyConstraintWhenMigrating: true, // 自动创建表的时候不创建外键
		SkipDefaultTransaction:                   false,
		NamingStrategy: schema.NamingStrategy{ // 自动创建表时候表名的配置
			SingularTable: true,
			// 全部的表名前面加前缀
			//TablePrefix: "mall_",
		},
	})
	if err != nil {
		panic("连接数据库失败")
	}
	// 这个要等生成dao再来配置,不配置也可以
	dao.SetDefault(db)
	fmt.Println("mysql启动成功...")
	return db
}

// TODO 文档地址: https://gorm.io/zh_CN/docs/
